package com.penghk.springbootdemo.service.impl;

import com.penghk.springbootdemo.Repository.PeopleRepositoty;
import com.penghk.springbootdemo.entity.People;
import com.penghk.springbootdemo.service.PeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class PeopleServiceImpl implements PeopleService {

    @Autowired
    PeopleRepositoty peopleRepositoty;

    @Override
    @Cacheable(value = "people" , key = "#name")
    public People findByName(String name) {
        return peopleRepositoty.findByName(name);
    }

    @Override
    @CacheEvict(value = "people" , key = "#name")
    public void removeByName(String name) {
        System.out.println("删除了key为" + name + "的数据缓存");
        //这里不做实际删除操作
    }

    @Override
    @CachePut(value = "people" , key = "#person.id")
    public People save(People person) {
        People p = peopleRepositoty.save(person);
        System.out.println("为id、key为:" + p.getId() + "数据做了缓存");
        return p;
    }

    @Override
    @CacheEvict(value = "people")
    public void remove(Long id) {
        System.out.println("删除了id、key为" + id + "的数据缓存");
        //这里不做实际删除操作
    }


    @Override
    @Cacheable(value = "people", key = "#person.id")//3
    public People findOne(People person) {
        People p = peopleRepositoty.findOne(person.getId());
        System.out.println("为id、key为:" + p.getId() + "数据做了缓存");
        return p;
    }

    @Override
    @Transactional(rollbackFor = {IllegalArgumentException.class})
    public People savePeopleWithRollback(People people) {
        People people1 = peopleRepositoty.save(people);
        if(people1.getName().equals("hello")) {
            throw new IllegalArgumentException("回滚数据");
        }
        return people1;
    }

    @Override
    @Transactional
    public People savePeopleWithOutRollback(People people) {
        return null;
    }
}
